/* eslint-disable */
// require("script-loader!file-saver");
import * as XLSX from "xlsx";
import * as XLSX_STYLE from "xlsx-style-vite"; // Vue3 + Vite


/*
 * parse xlsx content
 * @param singleRow: single row data
 */
const parseXlsx = (file, singleRow) => {
  if (!file) return [];

  return new Promise((resolve, reject) => {
    // create FileReader
    const reader = new FileReader();

    reader.onerror = (e) => {
      reader.abort();
      reject(new Error('ERROR: Failed to read file!\n\n' + reader.error));
    };

    reader.onload = (e) => {
      // parse data
      const data = e.currentTarget.result;
      const wb = XLSX.read(data, { type: 'binary' });

      // get first worksheet
      const wsname = wb.SheetNames[0];
      const ws = wb.Sheets[wsname];

      // convert array of arrays
      let arr;
      if (singleRow) {
        arr = XLSX.utils.sheet_to_json(ws, { header: 1 });
      } else {
        arr = XLSX.utils.sheet_to_json(ws, { defval: '' });
      }

      const result = singleRow ? arr.flat() : arr;

      resolve(result);
    };

    reader.readAsBinaryString(file);
  });
};

/*
 * export xlsx file
 */
const exportXlsx = (data, fn, colWidths, sn, sc, total) => {
  if (!data || data.length <= 0) return;

  return new Promise((resolve, reject) => {
    const sheetName = sn || '导入明细';
    const fileName = fn || '导入结果' + new Date().getTime() + '.xlsx';

    // transform data, create a worksheet
    const ws = XLSX.utils.json_to_sheet(data);

    if (colWidths && colWidths.length > 0) {
      ws['!cols'] = colWidths;
    }

    // col sum
    if (sc && sc.length > 0) {
      const l = data.length + 2;
      for (const i of sc) {
        ws[i + l] = total;
      }
    }

    // create a workbook
    const wb = XLSX.utils.book_new();

    // add data to workbook
    XLSX.utils.book_append_sheet(wb, ws, sheetName);

    // write file
    XLSX.writeFile(wb, fileName);

    resolve(fileName);

    // // write file
    // XLSX.writeFileAsync(fileName, wb, (err) => {
    //   if (err) {
    //     reject(err)
    //   } else {
    //     resolve(fileName)
    //   }
    // })
  });
};

function auto_width(ws, data) {
  /*set worksheet max width per col*/
  const colWidth = data.map(row => row.map(val => {
    /*if null/undefined*/
    if (val == null) {
      return { 'wch': 10 };
    }
    /*if chinese*/
    else if (val.toString().charCodeAt(0) > 255) {
      return { 'wch': val.toString().length * 2 };
    } else {
      return { 'wch': val.toString().length };
    }
  }))
  console.log(colWidth)
  /*start in the first row*/
  let result = colWidth[0];
  for (let i = 1; i < colWidth.length; i++) {
    for (let j = 0; j < colWidth[i].length; j++) {
      if (result[j]['wch'] < colWidth[i][j]['wch']) {
        result[j]['wch'] = colWidth[i][j]['wch'];
      }
    }
  }
  ws['!cols'] = result;
}


function json_to_array(key, jsonData) {
  return jsonData.map(v => key.map(j => { return v[j] || '' }));
}

const getCloumn = (title, fileData) => {
  const cloumn = []
  Object.entries(fileData).map(data => {
    if (title.includes(data[1].v)) {
      cloumn.push(data[0].replace(/\d/g, ''))
    }
  })
  return cloumn
}

const exportArray2excel = ({ key, data, title, filename, autoWidth, isMarkErr }) => {
  const wb = XLSX.utils.book_new();
  const arr = json_to_array(key, data);
  let tmp_data = {};
  // 组织数据
  arr.unshift(title)
  arr.forEach(function (value, r) {
    value.forEach(function (v, c) {
      var cell_obj = { c: c, r: r };
      var cell_text = XLSX.utils.encode_cell(cell_obj);
      tmp_data[cell_text] = {
        v: v,
      }
    })
  })
  // 查询失败行数
  const errLine = []
  data.forEach((e, ind) => {
    if (e.importStatus == '0' || e.status == 'INVALID') {
      // 因为有表头需要+2，EXCL是1开始所有
      errLine.push(ind + 2)
    }
  })

  // errorStyle
  const errorStyle = {
    font: {
      color: {
        rgb: "ffff0000",
      }
    }
    /* fill: {
        fgColor: {
            rgb: "ff0188FB",
        }
    },
    font: {
        sz: 14,
        color: {
            rgb: "ffffffff",
        }
    },
    border: {
        right: {
          style: "medium",
          color: {
              rgb: "FFFFFFFF",
          }
      },
    }, */
  }

  const autoWrap = {
    alignment: {
      wrapText: true,
      vertical: 'top',
      horizontal: 'left'
    },
  }

  //获取所有单元格编码,比如["A1", "B1", "C1", "D1", "E1", "F1"]
  var output_pos = Object.keys(tmp_data);
  var workbook = {
    SheetNames: ['sheet1'], //保存工作表的名称
    Sheets: {
      'sheet1': Object.assign({},
        tmp_data, //单元格内容
        {
          '!ref': output_pos[0] + ':' + output_pos[output_pos.length - 1] //工作表范围
        }),
    }
  };
  const cloumn = getCloumn(title, tmp_data)



  // 标记到处文件颜色
  if (isMarkErr) {
    Object.entries(tmp_data).map(data => {
      tmp_data[data[0]].s = autoWrap
      // 行
      errLine.forEach(line => {
        // 列
        cloumn.forEach(t => {
          // 列
          if (tmp_data[t.concat(line)]) {
            tmp_data[t.concat(line)].s = {
              ...tmp_data[t.concat(line)].s,
              ...errorStyle
            }
          }
        })
      })
    })
  }

  // 自动宽度处理
  // if(autoWidth){
  //   auto_width(tmp_data, arr);
  // }

  // 设置宽度
  if (autoWidth) {
    const colWidth = []
    cloumn.forEach((e, ind) => {
      colWidth.push({ wch: 20 })
    })
    workbook.Sheets.sheet1['!cols'] = colWidth
  }

  //导出文件
  var type = type || "xlsx";
  var filename = filename || "文件名";
  filename += "." + type;
  var wopts = {
    bookType: type,
    type: "binary",
  };
  var wbout = XLSX_STYLE.write(workbook, wopts);
  function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
  var blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" });
  function saveAs(obj, filename) {
    var link = document.createElement("a");
    link.download = filename;
    link.href = URL.createObjectURL(obj);
    link.click();
    URL.revokeObjectURL(obj);
  }
  saveAs(blob, filename);
}

const parseHeader = (file) => {
  let excelFile;
  if (!file) return [];
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (e) => {
      const data = e.target.result;
      excelFile = XLSX.read(data, { type: 'binary' });
      const headers_key = new Array();
      const headers = new Array();
      const str = XLSX.utils.sheet_to_json(excelFile.Sheets[excelFile.SheetNames[0]])
      for (let key in str[0]) {
        headers_key.push(key)
      }
      for (let i = 0; i < headers_key.length; i++) {
        headers.push(str[0][headers_key[i]])
      }
      console.log('headers', headers)
      resolve(headers)
    }
  })
}



export { parseXlsx, exportXlsx, exportArray2excel, parseHeader };
